<?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
//公共函数
function toDate($time, $format = 'Y-m-d H:i:s') {
    if (empty ( $time )) {
        return '';
    }
    $format = str_replace ( '#', ':', $format );
    return date ($format, $time );
}

function get_client_ip() {
    if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
        $ip = getenv ( "HTTP_CLIENT_IP" );
    else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
        $ip = getenv ( "HTTP_X_FORWARDED_FOR" );
    else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
        $ip = getenv ( "REMOTE_ADDR" );
    else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
        $ip = $_SERVER ['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
}
// 缓存文件
function cmssavecache($name = '', $fields = '') {
    $Model = D ( $name );
    $list = $Model->select ();
    $data = array ();
    foreach ( $list as $key => $val ) {
        if (empty ( $fields )) {
            $data [$val [$Model->getPk ()]] = $val;
        } else {
            // 获取需要的字段
            if (is_string ( $fields )) {
                $fields = explode ( ',', $fields );
            }
            if (count ( $fields ) == 1) {
                $data [$val [$Model->getPk ()]] = $val [$fields [0]];
            } else {
                foreach ( $fields as $field ) {
                    $data [$val [$Model->getPk ()]] [] = $val [$field];
                }
            }
        }
    }
    $savefile = cmsgetcache ( $name );
    // 所有参数统一为大写
    $content = "<?php\nreturn " . var_export ( array_change_key_case ( $data, CASE_UPPER ), true ) . ";\n?>";
    file_put_contents ( $savefile, $content );
}

function cmsgetcache($name = '') {
    return DATA_PATH . '~' . strtolower ( $name ) . '.php';
}
function getStatus($status, $imageShow = true) {
    switch ($status) {
        case 0 :
            $showText = '禁用';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
        case 2 :
            $showText = '待审';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/prected.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
        case - 1 :
            $showText = '删除';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1 :
        default :
            $showText = '正常';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';

    }
    return ($imageShow === true) ?  $showImg  : $showText;

}
function getDefaultStyle($style) {
    if (empty ( $style )) {
        return 'blue';
    } else {
        return $style;
    }

}
function IP($ip = '', $file = 'UTFWry.dat') {
    $_ip = array ();
    if (isset ( $_ip [$ip] )) {
        return $_ip [$ip];
    } else {
        import ( "ORG.Net.IpLocation" );
        $iplocation = new IpLocation ( $file );
        $location = $iplocation->getlocation ( $ip );
        $_ip [$ip] = $location ['country'] . $location ['area'];
    }
    return $_ip [$ip];
}

function getNodeName($id) {
    if (Session::is_set ( 'nodeNameList' )) {
        $name = Session::get ( 'nodeNameList' );
        return $name [$id];
    }
    $Group = D ( "Node" );
    $list = $Group->getField ( 'id,name' );
    $name = $list [$id];
    Session::set ( 'nodeNameList', $list );
    return $name;
}

function get_pawn($pawn) {
    if ($pawn == 0)
        return "<span style='color:green'>没有</span>";
    else
        return "<span style='color:red'>有</span>";
}
function get_patent($patent) {
    if ($patent == 0)
        return "<span style='color:green'>没有</span>";
    else
        return "<span style='color:red'>有</span>";
}


function getNodeGroupName($id) {
    if (empty ( $id )) {
        return '未分组';
    }
    if (isset ( $_SESSION ['nodeGroupList'] )) {
        return $_SESSION ['nodeGroupList'] [$id];
    }
    $Group = D ( "Group" );
    $list = $Group->getField ( 'id,title' );
    $_SESSION ['nodeGroupList'] = $list;
    $name = $list [$id];
    return $name;
}

function getCardStatus($status) {
    switch ($status) {
        case 0 :
            $show = '未启用';
            break;
        case 1 :
            $show = '已启用';
            break;
        case 2 :
            $show = '使用中';
            break;
        case 3 :
            $show = '已禁用';
            break;
        case 4 :
            $show = '已作废';
            break;
    }
    return $show;

}

function showStatus($status, $id) {
    switch ($status) {
        case 0 :
            $info = '<a href="javascript:resume(' . $id . ')">恢复</a>';
            break;
        case 2 :
            $info = '<a href="javascript:pass(' . $id . ')">批准</a>';
            break;
        case 1 :
            $info = '<a href="javascript:forbid(' . $id . ')">禁用</a>';
            break;
        case - 1 :
            $info = '<a href="javascript:recycle(' . $id . ')">还原</a>';
            break;
    }
    return $info;
}
//处理okhome 业务审核状态
function showCheckStatus($status, $id) {
    switch ($status) {
        case 0 :
            $info = '<a href="javascript:checkPass(' . $id . ')">审核</a>';
            break;
    }
    return $info;
}

/**
 +----------------------------------------------------------
 * 获取登录验证码 默认为4位数字
 +----------------------------------------------------------
 * @param string $fmode 文件名
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function build_verify($length = 4, $mode = 1) {
    return rand_string ( $length, $mode );
}


function getGroupName($id) {
    if ($id == 0) {
        return '无上级组';
    }
    if ($list = F ( 'groupName' )) {
        return $list [$id];
    }
    $dao = D ( "Role" );
    $list = $dao->findAll ( array ('field' => 'id,name' ) );
    foreach ( $list as $vo ) {
        $nameList [$vo ['id']] = $vo ['name'];
    }
    $name = $nameList [$id];
    F ( 'groupName', $nameList );
    return $name;
}
function sort_by($array, $keyname = null, $sortby = 'asc') {
    $myarray = $inarray = array ();
    # First store the keyvalues in a seperate array
    foreach ( $array as $i => $befree ) {
        $myarray [$i] = $array [$i] [$keyname];
    }
    # Sort the new array by
    switch ($sortby) {
        case 'asc' :
        # Sort an array and maintain index association...
            asort ( $myarray );
            break;
        case 'desc' :
        case 'arsort' :
        # Sort an array in reverse order and maintain index association
            arsort ( $myarray );
            break;
        case 'natcasesor' :
        # Sort an array using a case insensitive "natural order" algorithm
            natcasesort ( $myarray );
            break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key => $befree ) {
        $inarray [] = $array [$key];
    }
    return $inarray;
}

/**
 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '') {
    $str = '';
    switch ($type) {
        case 0 :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        case 1 :
            $chars = str_repeat ( '0123456789', 3 );
            break;
        case 2 :
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
            break;
        case 3 :
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        default :
        // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
            break;
    }
    if ($len > 10) { //位数过长重复字符串一定次数
        $chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 );
    }
    if ($type != 4) {
        $chars = str_shuffle ( $chars );
        $str = substr ( $chars, 0, $len );
    } else {
        // 中文随机字
        for($i = 0; $i < $len; $i ++) {
            $str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 );
        }
    }
    return $str;
}
function pwdHash($password, $type = 'md5') {
    return hash ( $type, $password );
}
/**
 * 得到配置变量的一维数组,根据状态如果是借出，未归还，未付等状态，自动显红返回。
 * 注意：系统配置变量中消费记录，借还记录的“未归还”，“借出”，“未付”如果变了，这里也要修改。
 */
function getConfigVal($key,$title) {
    $result = C($title);
    $returnStr = "";
    if(empty($key)) {
        if($result[0]=="未归还"||$result[0]=="借出" ||$result[0]=="未付") {
            $returnStr = '<font color="red">'.$result[0].'</font>';
            //$returnStr ="红色";
        }
        else {
            $returnStr = $result[0];
        }
    }
    else {//可能遇到0时会有问题TODO
        if($result[$key]=="未归还"||$result[$key]=="借出" ||$result[$key]=="未付") {
            $returnStr = '<font color="red">'.$result[$key].'</font>';
            //$returnStr ="红色";
        }
        else {
            $returnStr = $result[$key];
        }
    }
    return $returnStr;
}

function getSex($id) {
    switch ($id) {
        case 1:
            return '男';
            break;
        case 2:
            return '女';
            break;
        default:
            return '---';
    }
}

/**
 *通过模型的ID，默认获取名称，也可获取其他字段
 * @param <type> $id 模型主键
 * @param <type> $model 模型名称
 * @param <type> $field 获取的字段，默认为name
 * @return <type>
 */
function getModelName($id,$model,$field='name') {
    $id = intval($id);
    return M($model)->where('id='.$id)->getField($field);
}

//返回会员的帐号及姓名的链接
function getMemberFullNameLink($id){
    $result = M('Member')->where('id = '.intval($id))->field('account,name')->find();
    $fullName = $result['account'].'('.$result['name'].')';
    return '<a href="__APP__/Member/edit/id/'.$id.'">'.$fullName.'</a>';
}


function getAllMember(){
    $data = M('Member')->where('status = 1')->field('id,account,name')->findAll();
    $result = array();
    foreach($data as $key=>$value){
        $result[ $value['id'] ] = $value['account'].'('.$value['name'].')';
    }
    return $result;
    //ajaxReturn($data,'',1);
}

/**
 *返回产品的名称（公寓或房型）
 * @param <type> $type 0房型,1公寓
 */
function getPName($pid,$type){
  $model = $type==0 ? 'House':'Hotel';
  return getModelName($pid, $model);
}

function cutstr($string, $length = 100, $dot = ' ...') {
	$charset = 'utf-8';
	$string = preg_replace ('/\s+/m', ' ', $string);
	if (strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if (strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {
			$t = ord($string[$n]);
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n++;
				$noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n++;
			}
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
	} else {
		for ($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

//special for jquery ui autocomplete remote datasource
function array_to_json( $array ){

    if( !is_array( $array ) ){
        return false;
    }

    $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if( $associative ){

        $construct = array();
        foreach( $array as $key => $value ){

            // We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
            if( is_numeric($key) ){
                $key = "key_$key";
            }
            $key = "\"".addslashes($key)."\"";

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "\"".addslashes($value)."\"";
            }

            // Add to staging array:
            $construct[] = "$key: $value";
        }

        // Then we collapse the staging array into the JSON form:
        $result = "{ " . implode( ", ", $construct ) . " }";

    } else { // If the array is a vector (not associative):

        $construct = array();
        foreach( $array as $value ){

            // Format the value:
            if( is_array( $value )){
                $value = array_to_json( $value );
            } else if( !is_numeric( $value ) || is_string( $value ) ){
                $value = "'".addslashes($value)."'";
            }

            // Add to staging array:
            $construct[] = $value;
        }

        // Then we collapse the staging array into the JSON form:
        $result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return $result;
}

  /**
     *判断是否该房间已经有人预订或入住
     * @param <type> $startTime 入住时间或离开时间
   * @param <type> $TransId 入住单的ID或预订单ID，适用于更新时，防止与自身比较
     */
    function isOverlap($room_id,$startTime,$endTime,$TransId){
        $ordermap['room_id'] = $room_id;
        if(!empty( $TransId )){//排除自身
            $ordermap['id'] = array('neq',$TransId);
        }
        $ordermap['status'] = array('between','3,4');//只关注预订定金或口头确定的状态
        $result = M('Order')->where($ordermap)->findAll();
        $isOverlap = false;
        foreach ($result as $value) {
            $start_time = $value['start_time'];
            $end_time = $value['end_time'];
            if( ($startTime >= $start_time) && ($startTime <= $end_time) ){//交叉关系
                $isOverlap = true;
                break;
            }
            if( ($endTime >= $start_time) && ($endTime <= $end_time) ){//交叉关系
                $isOverlap = true;
                break;
            }
            if( ($startTime < $start_time) && ($endTime > $end_time) ){//包含关系
                $isOverlap = true;
                break;
            }
        }
        if($isOverlap){
            return true;
        }else {//入住单情况
            $map['room_id'] = $room_id;
            if(!empty( $TransId )) {//排除自身
                $map['id'] = array('neq',$TransId);
            }
            $result = M('Checkin')->where($map)->findAll();
            foreach ($result  as $v2) {
                $start_time = $v2['start_time'];
                $end_time = $v2['end_time'];
               $end_realtime = $v2['end_realtime'];
               if($end_realtime == 0){//无实际离开时间
                     if( ($startTime >= $start_time) && ($startTime <= $end_time) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($endTime >= $start_time) && ($endTime <= $end_time) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($startTime < $start_time) && ($endTime > $end_time) ) {//包含关系
                       $isOverlap = true;
                       break;
                   }

               }
               else{//有实际离开时间
                        if( ($startTime >= $start_time) && ($startTime <= $end_realtime) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($endTime >= $start_time) && ($endTime <= $end_realtime) ) {
                       $isOverlap = true;
                       break;
                   }
                   if( ($startTime < $start_time) && ($endTime > $end_realtime) ) {//包含关系
                       $isOverlap = true;
                       break;
                   }
               }
               
            }
            return $isOverlap;
        }
       
    }
   
    //统计该会员的入住单数
    function count_checkin($member_id=''){
        return M('Checkin')->where('member_id ='.$member_id)->count('id');
    }
  

    //统计该会员的入住单数 + 链接
    function count_checkin_link($member_id=''){
        $count = M('Checkin')->where('member_id ='.$member_id)->count('id');
        $member_name = getModelName($member_id,'member');
        return '<a href="__APP__/Checkin/index/member_id/'.$member_id.'" target="_blank">'.$count.'</a>';
    }

    //统计该会员的订单数 + 链接
    function count_order_link($member_id=''){
        $count = M('Order')->where('member_id ='.$member_id)->count('id');
        //$member_name = getModelName($member_id,'member');
        return '<a href="__APP__/Order/index/member_id/'.$member_id.'" target="_blank">'.$count.'</a>';
    }

     //统计该会员的留言数 + 链接
    function count_msg_link($member_id=''){
        $count_member = M('Comment')->where('member_id ='.$member_id.' and user_id=0 and parent=0')->count('id');//会员留言数
        $count_sys = M('Comment')->where('member_id ='.$member_id.' and user_id !=0 and parent=0')->count('id');//后台发给会员的消息数
        //$member_name = getModelName($member_id,'member');
        return '<a href="__APP__/Comment/index/member_id/'.$member_id.'" target="_blank" title="会员留言">'.$count_member.'</a> |
            <a href="__APP__/Comment/index/member_id/'.$member_id.'/msgtype/1" target="_blank" title="公寓留言"><span style="color:red;">'.$count_sys.'</span></a>';
    }
    //通过入住或预订单ID返回相应的入住单号或预订单号及链接,type=1为入住，0为预订
      function checkin_no_link($obj_id='',$type=1){
        $obj_no = getManNo($obj_id,$type);
        //$member_name = getModelName($member_id,'member');
        if($type== 1) {
            return '<a href="__APP__/Checkin/edit/id/'.$obj_id.'" target="_blank">'.$obj_no.'</a>';
        }else {
            return '<a href="__APP__/Order/edit/id/'.$obj_id.'" target="_blank">'.$obj_no.'</a>';
        }
    }

    function getCheckInfo($checkin_id="",$type=""){
        return $member_name = getModelName($checkin_id, 'Checkin',$type);
    }
    //获取当前公寓下属的房型列表链接
    function hotel_children_link($obj_id=''){
        $count_house = M('House')->where('hotel_id ='.$obj_id)->count();
         return '<a href="__APP__/House/index/hotel_id/'.$obj_id.'">下属房型('.$count_house.')</a>';
    }

    /**
     * 返回该model的编辑链接，类似于 member/edit/id/$id
     * @param <type> $id
     * @param <type> $model
     * @param <type> $field 超链接显示的锚文本字段
     * @return <type>
     */
    function model_edit_link($id,$model,$field='name') {
    $id = intval($id);
    $title = M($model)->where('id='.$id)->getField($field);
    return '<a href ="__APP__/'.$model.'/edit/id/'.$id.'">'.$title.'</a>';
    }

    function getConfigDataJson($cfg_name,$id_name,$value_name){
        $configArray = C($cfg_name);
        $newJson = "[";
        $arrLength = count($configArray);
        for($i=0;$i< $arrLength;$i++){
            if($i == $arrLength-1){//最后一个
                $newJson .="{".$id_name.":\"".$i."\",".$value_name.":\"".$configArray[$i]."\"}]";
            }else{
                $newJson  .="{".$id_name.":\"".$i."\",".$value_name.":\"".$configArray[$i]."\"},";
            }
        }
        echo $newJson;
    }

    /**
     * 返回所有公寓的房型，房间树,
     * return json data
     */
    function getHotelTreeJson(){
        $newJson = "[";
        $hotels = M('Hotel')->where('status = 1')->order('sort asc')->findAll();
        $length1 = count($hotels);
        foreach($hotels as $key => $value){
            $newJson .= "{\"id\":\"ht".$value['id']."\",\"text\":\"".$value['name']."\"";
            //$newJson .= "{\"id\":\"ht".$value['id']."\",\"text\":\"".$value['name']."\",\"state\":\"closed\"";
            $houses = M('House')->where('hotel_id ='.$value['id'].' and status = 1')->order('sort asc')->findAll();
            if($houses){//有房型
                $newJson .= ",\"state\":\"closed\",
                    \"children\":[";
                $length2 = count($houses);
                foreach ($houses as $key2 => $value2) {
                    $newJson .= "{\"id\":\"hu".$value2['id']."\",\"text\":\"".$value2['name']."\"";
                    $rooms = M('Room')->where('house_id ='.$value2['id'].' and status = 1')->order('sort asc')->findAll();
                    if($rooms) {//取房间
                        $newJson .= ",
                    \"children\":[";
                        $length3 = count($rooms);
                        foreach ($rooms as $key3 => $value3) {
                            if($key3 == ($length3 -1 ) ){//最后一个节点
                                $newJson .= "{\"id\":\"rm".$value3['id']."\",\"text\":\"".$value3['room_no']."\"}]}";
                            }else{
                                 $newJson .= "{\"id\":\"rm".$value3['id']."\",\"text\":\"".$value3['room_no']."\"},";
                            }
                            
                        }
                    }else{//没有房间
                        $newJson .= "}";
                    }
                    if ($key2 < ($length2 - 1 )) {
                       $newJson .= ",";
                    } else {//最后一个节点
                       $newJson .= "]}";//TODO
                    }
                }
            } else {//没有房型
                $newJson .= "}";
            }
            if ($key < ($length1 - 1 )) {
               $newJson .= ",";
            } else {//最后一个节点
               $newJson .= "]";//整个json树结束
            }
        }

        echo $newJson;
    }

    function jsonFilter($sourceStr) {
        $sourceStr = str_replace("\\", "\\\\", $sourceStr);
        $sourceStr = str_replace("\b", "\\\b", $sourceStr);
        $sourceStr = str_replace("\t", "\\\t", $sourceStr);
        $sourceStr = str_replace("\n", "\\\n", $sourceStr);
        $sourceStr = str_replace("\n", "\\\n", $sourceStr);
        $sourceStr = str_replace("\f", "\\\f", $sourceStr);
        $sourceStr = str_replace("\r", "\\\r", $sourceStr);
        $sourceStr = str_replace("\r\n", "\\r\\n",$sourceStr);//替换换行
        $sourceStr = str_replace(chr(13),' ',$sourceStr);//回车
	$sourceStr = str_replace(chr(10),' ',$sourceStr);//换行
        return str_replace("\"", "\\\"", $sourceStr);
    }

    //返回该入住单的消费记录及借还记录的详情链接
    function other_detail_link($checkin_id){
        return '<a href="__URL__/other_detail/id/'.$checkin_id.'">消费借还记录</a>';
    }

    /**
 * 一次给多个用户发送邮件,
 */
function multiSendMail($subject='',$message='',$from='',$to='') {
	$from = preg_replace('/\v*/', '', $from);
	if (empty($from) || empty($to)) {
		return false;
	}
	$to = explode(',',preg_replace('/\v*/', '', $to.','.C('SERVEEMAIL')));
	foreach($to as $value) {
		if (!empty($value)) {
			sendMail($subject,$message,$from,$value);
		}
	}
}

// 参数设置 string $subject, string $message, 'name <name@server.suffix>' $from, 'name1 <name1@server1.suffix>,name2 <name2@server2.suffix>....' $to
function sendMail($subject='',$message='',$from='',$to='') {
	if (empty($subject) || empty($to)) {
		throw new Exception('参数错误');
	}
	$mail = array(
			'charset' => "UTF-8",
			'adminemail' => "info@okhome.cn",
			'sendmail_silent' => 1,
			'maildelimiter' => 1,
			'mailusername' => 1,
			'mailsubject' => $subject,
			'mailmessage' => $message,
			'from' => $from,
			'mailto' => $to,
			'server' => "smtp.exmail.qq.com",
			'port' => 25,
			'mailsend' => 2,
			'auth' => 1,
			'auth_username' => 'info@okhome.cn',
			'auth_password' => 'lm62660009',
	);

	if($mail['sendmail_silent']) {
		error_reporting(0);
	}

	$email_from = $mail['from'];
	$email_to = $mail['mailto'];
	$charset = isset($mail['charset']) ? $mail['charset'] : 'UTF-8';
	$maildelimiter = $mail['maildelimiter'] == 1 ? "\r\n" : ($mail['maildelimiter'] == 2 ? "\r" : "\n");
	$mailusername = isset($mail['mailusername']) ? $mail['mailusername'] : 1;

	$email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', $mail['mailsubject']))).'?=';
	$email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $mail['mailmessage'])))))));

	$email_from = $email_from == '' ? '=?'.$charset.'?B?'.base64_encode('管理员')."?= <".$mail['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$charset.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);

	foreach(explode(',', $email_to) as $touser) {
		$tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$charset.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
	}
	$email_to = implode(',', $tousers);

	$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Mailman{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=$charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";

	$mail['port'] = $mail['port'] ? $mail['port'] : 25;

	if($mail['mailsend'] == 1 && function_exists('mail')) {

		@mail($email_to, $email_subject, $email_message, $headers);

	} elseif($mail['mailsend'] == 2) {

		if(!$fp = fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
			throw new Exception('SMTP ', "($mail[server]:$mail[port]) CONNECT - Unable to connect to the SMTP server", 0);
		}
		stream_set_blocking($fp, true);

		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220') {
			throw new Exception('SMTP '."$mail[server]:$mail[port] CONNECT - $lastmessage");
		}

		fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." Mailman\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) HELO/EHLO - $lastmessage");
		}

		while(1) {
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
				break;
			}
			$lastmessage = fgets($fp, 512);
		}

		if($mail['auth']) {
			fputs($fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) AUTH LOGIN - $lastmessage");
			}

			fputs($fp, base64_encode($mail['auth_username'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) USERNAME - $lastmessage");
			}

			fputs($fp, base64_encode($mail['auth_password'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 235) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) PASSWORD - $lastmessage");
			}

			$email_from = $mail['from'];
		}

		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250) {
				throw new Exception('SMTP '."($mail[server]:$mail[port]) MAIL FROM - $lastmessage");
			}
		}

		$email_tos = array();
		foreach(explode(',', $email_to) as $touser) {
			$touser = trim($touser);
			if($touser) {
				fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
				$lastmessage = fgets($fp, 512);
				if(substr($lastmessage, 0, 3) != 250) {
					fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
					$lastmessage = fgets($fp, 512);
					throw new Exception('SMTP '."($mail[server]:$mail[port]) RCPT TO - $lastmessage");
				}
			}
		}

		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) DATA - $lastmessage");
		}
                //将gmdate改为date，以使用当前时区
		$headers .= 'Message-ID: <'.date('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";
                fputs($fp, "Date: ".date('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			throw new Exception('SMTP '."($mail[server]:$mail[port]) END - $lastmessage");
		}

		fputs($fp, "QUIT\r\n");

	} elseif($mail['mailsend'] == 3) {

		ini_set('SMTP', $mail['server']);
		ini_set('smtp_port', $mail['port']);
		ini_set('sendmail_from', $email_from);

		@mail($email_to, $email_subject, $email_message, $headers);

	}
}

//绘制县列表
function makeCountry($selected) {
	$lists = M("Country")->select();
	$select = "<select name='coun_code' id='coun_code'>";
	if(0 == $selected) {
		$select .= "<option value='-1'>请选择城市</option>";
	}
        $result = M("Country")->field("city_code")->where("coun_code={$selected}")->find();
	$lists = M("Country")->where("city_code={$result['city_code']}")->select();
	foreach($lists as $value) {
		if($selected == $value["coun_code"]) {
			$select .= "<option value='{$value['coun_code']}' selected>{$value['coun_name']}</option>";
		}else {
			$select .= "<option value='{$value['coun_code']}'>{$value['coun_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}

//绘制省列表
function makeProvince($selected) {
	$lists = M("Province")->select();
	$select = "<select name='prov_code' id='prov_code' onchange='modifyCity(this);'>";
	if(0 == $selected) {
		$select .= "<option value='-1'>请选择省</option>";
	}
	foreach($lists as $value) {
		if($selected == $value["prov_code"]) {
			$select .= "<option value='{$value['prov_code']}' selected>{$value['prov_name']}</option>";
		}else {
			$select .= "<option value='{$value['prov_code']}'>{$value['prov_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}
//绘制城市列表
function makeCity($selected) {
	if(0 == $selected) {
		return "<select id='city_code' name='city_code' onchange='modifyCountry(this);'><option value='-1'>请选择省</option></select>";
	}
	$select = "<select id='city_code' name='city_code' onchange='modifyCountry(this);'>";
	$result = M("City")->field("prov_code")->where("city_code={$selected}")->find();
	$lists = M("City")->where("prov_code={$result['prov_code']}")->select();
	foreach($lists as $value) {
		if($selected == $value["city_code"]) {
			$select .= "<option value='{$value[city_code]}' selected>{$value['city_name']}</option>";
		}else {
			$select .= "<option value='{$value[city_code]}'>{$value['city_name']}</option>";
		}
	}
	$select .= "</select>";
	return $select;
}

/**
 *通过产品编号获取对应的单位
 * //TODO 做成通用性
 * @param <type> $pid
 */
function getProductUnit($pid){
    $unit_id = getModelName($pid, 'Product', 'unit_id');
    return getModelName($unit_id, 'Unit');
}

function getStock($product_id,$specification){
    $map = array(
        'product_id' => $product_id,
        'specification' => $specification
        );
    $number = M('Stock')->where($map)->getField('number');
    return empty($number)?0 : $number;
}

//返回Model id,name.volist使用时，$key ,$vo
  function getModelIdName($model,$map="status = 1",$sort=""){
    $model = ucfirst(strtolower($model));//首字母大写
    if(!empty($sort))
        return M($model)->where($map)->order($sort)->getField('id,name');
    else
        return M($model)->where($map)->getField('id,name');
  }

/*获取表的字段值，相对getModelIdName更灵活些，volist 使用时，二维数组 vo.id,vo.name...vo.field
**@field 多个字段使用,隔开
**/
function getModelField($model,$field ='id,name',$map="status = 1",$sort="",$limit=""){
    $model = ucfirst(strtolower($model));//首字母大写
    if(!empty($sort) && empty($limit) )
        return M($model)->where($map)->order($sort)->field($field)->findAll();
    elseif(!empty($sort) && !empty($limit) )
        return M($model)->where($map)->order($sort)->field($field)->limit($limit)->findAll();
    elseif(empty($sort) && !empty($limit) )
        return M($model)->where($map)->field($field)->limit($limit)->findAll();
    else
        return M($model)->where($map)->field($field)->findAll();
  }

/**返回对应model select html list
** @mod 类型，如user,supplier,unit
**@void 当前model vo.id,if eq,then selected
**@ class 默认当前的select 宽度 span2
**/
function modList($mod,$void = -1,$class='span2',$name=''){
    if(empty($mod)){
        echo 'None Type';
        return false;
    }
        
    $lowcase_mod = strtolower($mod);
    $fupcase_mod = ucfirst($lowcase_mod);

    $lists = getModelIdName($fupcase_mod);
    if(empty($name))
        $name = empty($name)? $lowcase_mod.'_id' : $name; //默认变量名mod_id

    $selectStr = ' <select name="'.$name.'" class="'.$class.'">';
    $selectStr .= '<option value="">--请选择--</option>';
    foreach ($lists as $key => $value) {
        $selectStr.='<option value="'.$key.'"';
        if($lowcase_mod == 'user' && ($_SESSION[C('USER_AUTH_KEY')] == $key ) && $void != '' )
            $selectStr.='selected ';
        else if($void == $key && $void != '' )
            $selectStr.='selected ';

        $selectStr.='>'.$value.'</option>';
    }
    $selectStr .= '</select>';
    return $selectStr;
}
/***
** 返回配置变量的select html list
**@mod 配置的变量名，如orderStatus
**@name 返回的select name .默认为status
**@void 当前model vo.id,if eq,then selected
**@class 默认当前的select 宽度 span2
**/
function configList($mod,$void = -1,$name='status', $class='span2' ){
    $selectStr = '<select name="'.$name.'" class="'.$class.'"">';
    $selectStr .= '<option value="">--请选择--</option>';
    foreach ($mod as $key => $value) {
        $selectStr.='<option value="'.$key.'"';
        if($void == $key && $void !== '' && $void !== NULL )
            $selectStr.='selected ';
        $selectStr.='>'.$value.'</option>';
    }
    $selectStr .= '</select>';
    return $selectStr;
}

//获取产品英文名
function getPename($id){
    return getModelName($id,'Product','ename');
}

//获取产品CAS
function getCas($id){
      return getModelName($id,'Product','cas');
}

//返回对应询单的采购询价链接
 function getAskLink($id){
      $ask = M('Ask_supplier')->where('inquiry_id = '.$id)->find();
      if(is_array($ask))
      return '<a href="__APP__/Ask_supplier/edit/id/'.$ask['id'].'">'.$ask['mano'].'('.getConfigVal($ask['status'],'askStatus').')</a>';
}

//返回对应询单的采购询价状态
 function getAskStatus($id){
      $ask = M('Ask_supplier')->where('inquiry_id = '.$id)->find();
      if(is_array($ask))
            return getConfigVal($ask['status'] , 'askStatus');
      else
            return '';
}

//get contact man phone,email,mobile etc
function getContactInfo($cid){
     $contact = M('Contact')->where('id = '.$cid)->find();
     if(!empty($contact))
       return $contact['name'].' 手机：'.$contact['mobile']. ' 电话：'.$contact['phone'].' QQ:'.$contact['qq'];
     else
        return ;
}

function getShippingDetail($shipping_id='')
{
    $shipping_detail = M('shipping_detail')->where('shipping_id = '.$shipping_id)->findAll();
    if(!is_array($shipping_detail))
        return '';
    $detail = '';
    foreach ($shipping_detail as $key => $value) {
        $detail .= getModelName($value['order_detail_id'],'Order_detail','mano').': ';
        $product = M('Product')->getById($value['product_id']);
        $detail .= $product['name'].'; '.$product['ename'].'; '.$product['cas'].'净重：'.$value['number'] .'<br>';
    }
    return '<a href="__URL__/detail/id/'.$shipping_id.'">'. $detail .'</a>';
}

//get customer info include:company+contact man
function getCustomerInfo($cid){
     $contact = M('Customer')->where('id = '.$cid)->find();
     if(!empty($contact))
       return $contact['company'].';'.$contact['name'];
     else
        return ;
}

function getMsg($order_detail_id='')
{
    $msgs = M('Message')->where('obj_type ="Order_detail" and obj_id = '.$order_detail_id)->order('id desc')->findAll();
    $str = "";
    foreach ($msgs as $key => $value) {
        $str .= $value['id'].'<i class=\'icon-comment\'></i> '.$value['content'].' ;'.getModelName($value['user_id'],'User').'('.$value['depart'].') '.toDate($value['update_time'],'m-d H:i')."<br />";
    }
    return $str;
}

function getMsgTip($order_detail_id){
    $msg = getMsg($order_detail_id);
   $msgTip = '<a href="#" rel="popover" class="btn" data-content="'.$msg.'" data-original-title="备注">备注</a>';
   return $msgTip;
}
function showMoreTip($str){
   $msgTip = '<a href="#" rel="popover" class="btn" data-content="'.$str.'" data-original-title="详情">详情</a>';
   return $msgTip;
}

//return product name and ename
function getPfullName($pid){
    $product = M('Product')->getById($pid);
    if(!$product)
        return;
    else
       return $product['name'].' ; '.$product['ename'];
}

//return supplier rank and name
function getSupplierAndRank($sid='')
{
    $supplier = M('Supplier')->getById($sid);
    if(!$supplier)
        return;
    else
       return $supplier['name'].' ('.getConfigVal($supplier['rank'],C('supplier_rank')).')';
}

//数字转为人民币大写金额
function toCNcap($data){
   $capnum=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");
   $capdigit=array("","拾","佰","仟");
   $subdata=explode(".",$data);
   $yuan=$subdata[0];
   $j=0; $nonzero=0;
   for($i=0;$i<strlen($subdata[0]);$i++){
      if(0==$i){ //确定个位 
         if($subdata[1]){ 
            $cncap=(substr($subdata[0],-1,1)!=0)?"元":"元零";
         }else{
            $cncap="元";
         }
      }   
      if(4==$i){ $j=0;  $nonzero=0; $cncap="万".$cncap; } //确定万位
      if(8==$i){ $j=0;  $nonzero=0; $cncap="亿".$cncap; } //确定亿位
      $numb=substr($yuan,-1,1); //截取尾数
      $cncap=($numb)?$capnum[$numb].$capdigit[$j].$cncap:(($nonzero)?"零".$cncap:$cncap);
      $nonzero=($numb)?1:$nonzero;
      $yuan=substr($yuan,0,strlen($yuan)-1); //截去尾数	  
      $j++;
   }

   if($subdata[1]){
     $chiao=(substr($subdata[1],0,1))?$capnum[substr($subdata[1],0,1)]."角":"零";
     $cent=(substr($subdata[1],1,1))?$capnum[substr($subdata[1],1,1)]."分":"零分";
   }
   $cncap .= $chiao.$cent."整";
   $cncap=preg_replace("/(零)+/","\\1",$cncap); //合并连续“零”
   return $cncap;
 }

?>
